package com.wty.design.creational.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author wangtengyu
 * @Create 2018-09-18-16:41
 */
public class ReflectTest {
    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, NoSuchFieldException {
        Class clazz=DoubleCheckSingleton.class;
        Constructor con = clazz.getDeclaredConstructor();
        con.setAccessible(true);
        //反射调用了无参构造，但是反射的构造并没有改变类中instance的值
        DoubleCheckSingleton instance = (DoubleCheckSingleton) con.newInstance();

        //在把falg字段修改了，这样又能反射攻击了嘻嘻嘻
//        Field flagField=clazz.getDeclaredField("flag");
//        flagField.setAccessible(true);
//        flagField.set(instance,true);

        //getInstance是调用了无参构造，但是改变了instance的值
        DoubleCheckSingleton instance2=DoubleCheckSingleton.getInstance();
        System.out.println(instance==instance2);
        System.out.println(instance);




//        //非懒加载
//        Class clazz=StaticInnerClassSingleton.class;
//        Constructor con = clazz.getDeclaredConstructor();
//        con.setAccessible(true);
//        //反射调用了无参构造，但是反射的构造并没有改变类中instance的值
//        StaticInnerClassSingleton instance = (StaticInnerClassSingleton) con.newInstance();
//        //getInstance是调用了无参构造，但是改变了instance的值
//        StaticInnerClassSingleton instance2=StaticInnerClassSingleton.getInstance();
//        System.out.println(instance==instance2);
//        System.out.println(instance);
    }
}
